package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/aliyun/fc-runtime-go-sdk/fc"
	"github.com/joho/godotenv"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	db    *gorm.DB
	sqlDB *sql.DB
)

type QueryParams struct {
	SchoolId string `json:"school_id,omitempty"`
	Time     string `json:"time,omitempty"`
}

type Student struct {
	StuId        string    `json:"stu_id,omitempty"`
	StuLoginname string    `json:"stu_loginname,omitempty"`
	SchoolId     string    `json:"school_id,omitempty"`
	StuRegTime   time.Time `json:"stu_reg_time,omitempty"`
}

func (Student) TableName() string {
	return "student"
}

func initialize(ctx context.Context) {
	// 加载 .env 文件中的环境变量（本地开发时使用）
	if err := godotenv.Load(); err != nil {
		log.Printf("Warning: .env file not found or failed to load, assuming environment variables are set externally: %v", err)
		// 注意：在阿里云函数计算环境中，不会存在 .env 文件，这是正常的。
		// 所以这里仅打印警告，不终止程序。
	}

	dbUser := os.Getenv("MYSQL_USER")
	dbPassword := os.Getenv("MYSQL_PASSWORD")
	dbEndpoint := os.Getenv("MYSQL_ENDPOINT")
	dbPort := os.Getenv("MYSQL_PORT")
	dbName := os.Getenv("MYSQL_DBNAME")

	if dbUser == "" || dbPassword == "" || dbEndpoint == "" || dbPort == "" || dbName == "" {
		log.Fatal("Missing required environment variables for database connection")
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbUser, dbPassword, dbEndpoint, dbPort, dbName)

	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to MySQL: %v", err)
	}

	sqlDB, err = db.DB()
	if err != nil {
		log.Fatalf("Failed to get database connection pool: %v", err)
	}

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)

	log.Println("Database connection initialized successfully")
}

type Response struct {
	Message string `json:"message"`
	Count   int64  `json:"count,omitempty"`
}

func HandleHttpRequest(ctx context.Context, event QueryParams) (Response, error) {
	if db == nil {
		// 如果 db 仍未初始化，直接返回错误
		return Response{Message: "database not initialized"}, fmt.Errorf("database not initialized")
	}

	// 检查数据库连接是否有效（可选）
	if err := sqlDB.PingContext(ctx); err != nil {
		log.Printf("Database connection failed: %v", err)
		return Response{Message: "database connection failed"}, err
	}

	query := db.Model(&Student{})
	if event.SchoolId != "" {
		query = query.Where("school_id = ?", event.SchoolId)
	}
	if event.Time != "" {
		parseTime, err := time.Parse("2006-01-02", event.Time)
		if err != nil {
			return Response{Message: "failed to parse time"}, fmt.Errorf("failed to parse time: %v", err)
		}
		query = query.Where("stu_reg_time >= ?", parseTime)
	}

	var count int64
	result := query.Count(&count)
	if result.Error != nil {
		return Response{Message: "database query failed"}, result.Error
	}

	return Response{
		Message: "Query successful",
		Count:   count,
	}, nil
}

func preStop(ctx context.Context) {
	if sqlDB != nil {
		err := sqlDB.Close()
		if err != nil {
			log.Printf("ERROR: Could not close MySQL connection: %v", err)
		} else {
			log.Println("Database connection closed successfully")
		}
	}
}

func main() {
	fc.RegisterInitializerFunction(initialize)
	fc.RegisterPreStopFunction(preStop)
	fc.Start(HandleHttpRequest)

}
